/*
 * Created by Administrator on 2017/3/14.
 */
var Button = require('../button/index');
//查询样式是否存在
function hasClass(elem, cls) {
    elem = elem || {};
    return new RegExp("\\b" + cls + "\\b").test(elem.className);
}
//添加样式
function addClass(elem, cls) {
    elem = elem || {};
    hasClass(elem, cls) || (elem.className += " " + cls);
    elem.className = elem.className.replace(/^\s|\s$/g, "").replace(/\s+/g, " ");
}
//删除样式
function removeClass(elem, cls) {
    elem = elem || {};
    if (hasClass(elem, cls)) {
        elem.className = elem.className.replace(new RegExp("(\\s|^)" + cls + "(\\s|$)"), "");
    }
};
//obj为要绑定事件的元素，ev为要绑定的事件，fn为绑定事件的函数
function myAddEvent(obj, ev, fn) {
    if (obj.attachEvent) {
        obj.attachEvent("on" + ev, fn);
    }
    else {
        obj.addEventListener(ev, fn, false);
    }
}
function myRemoveEvent(obj, ev, fn) {
    if (obj.attachEvent) {
        obj.detachEvent("on" + ev, fn);
    }
    else {
        obj.removeEventListener(ev, fn, false);
    }
}
/**
 * Layer组件
 * @class Layer
 * @extends Complex
 *
 * @param [title] 标题
 * @param [type] 三种特殊情况text,success,failure
 * @param [width] 窗口宽
 * @param [height] 窗口高
 * @param [className] 窗口类名
 * @param [showClose] 显示关闭按钮，默认为true
 * @param [closeBack] 关闭回调
 * @param [autoClose] 是否自动关闭窗口，数值型，单位为秒，默认为0不自动关闭；
 * @param [position] css样式位置，默认为fixed；只有absolute和fixed两种；
 * @param [confirm] 确定按钮文本，默认为空即不显示；
 * @param [confirmBack] 点击确定按钮后执行的函数，仅当confirm不为空时才会触发回调confirmback函数；当回调为空时，点击确定后默认关闭窗口；
 * @param [cancel] 取消按钮文本，默认为空即不显示；
 * @param [cancelBack] 取消回调，跟确定一样
 * @param [afterBack] 窗口加载完时执行的函数
 * @param [move] 允许窗口拖动，默认为false；
 * @param [maskLayer] 显示遮罩层
 * @param [shadeClose] 默认为false;点击遮罩关闭 false不关闭
 * @param [animation] 弹出层css3动画效果，仅在支持的浏览器，默认为1。动画序号对应animation样式的layer-anim-*
 *
 * 示例:
 *
 *     @example
 *
 *      <Layer title="222">content</Layer>
 *
 *      <Layer title="提交成功" type="success" confirm="确认">
 *        恭喜，提交成功，点击确认关闭窗口
 *      </Layer>
 *
 *      <Layer title="提交失败" type="failure" confirm="确认" width="500">
 *          <p>抱歉抱歉，提交失败，点击确认关闭窗口</p>
 *          <p>失败原因：失败原因失败原因失败原因失败原因</p>
 *      </Layer>
 * */
var Layer = React.createClass({
    getDefaultProps: function () {
        return {
            getContainer:'',
            display: false,
            type: "",
            width: "",
            height: "",
            className: "",
            showClose: true,
            closeBack: "",
            position: "fixed",
            confirm: "",
            confirmBack: "",
            cancel: "",
            cancelBack: "",
            afterBack: "",
            animation: "layer-anim-1",
            maskLayer: true,
            shadeClose: false,
            move: false,
            autoClose: 0,
            id: "",
            left: "",
            top: "",
            contentHeight: "" //内容区域高
        }
    },
    getInitialState: function () {
      return{
          display:this.props.display ? 'block':'none'
      }
    },
    componentDidMount: function () {

        myAddEvent(window, 'resize', this._handleResize.bind(this));
    },
    /**
     * Layer弹出
     * this.refs.layer.layerOpen();
     * */
    layerOpen: function () {
        var _this = this;
        // this.refs.ucslayer.style.display = "block";
        this.setState({display:'block'});
        addClass(this.refs.ucslayer,this.props.animation);
        this._setPosition();
        //添加遮罩层
        this.props.maskLayer ? this._maskLayer() : "";
        //窗口加载完回调
        this.props.afterBack ? this.props.afterBack() : "";
        //计算倒计时
        this.props.autoClose > 0 ? this._handleCountdown() : "";
    },
    /**
     * Layer关闭
     * this.refs.layer.layerＣlose();
     * */
    layerClose: function () {
        var _this = this;
        // this.refs.ucslayer.style.display = "none";
        this.setState({display:'none'});
        removeClass(_this.refs.ucslayer,_this.props.animation);
        //移除遮罩层
        this.getContainer.removeChild(_this.divEL);
        if (this.props.shadeClose) {
            myRemoveEvent(_this.divEL, 'click', this._handleMaskLayerClick);
            //this.divEL.removeEventListener('click', this._handleMaskLayerClick);
        }
        // this.props.closeBack ? this.props.closeBack() : "";
        clearInterval(this.timer);
    },
    _handleResize: function () {
        //console.log("窗口改变");//传个参数进去，浏览器窗口缩放时不修改弹出层的宽高，只调整位置保持居中
        //确保窗口在显示状态才执行缩放，隐藏下取不到高
        this.state.display === "block" ? this._setPosition("resize") : "";
    },
    _handleCountdown: function () {
        var _this = this;
        //倒计时
        clearInterval(this.timer);
        var i = this.props.autoClose;
        this.timer = setInterval(function () {
            i--;
            this.refs.autoClose.innerHTML = i;
            if (i == 0) {
                this.layerClose();
                _this._autoCloseBack();
            }
        }.bind(this), 1000);
    },
    _autoCloseBack:function () {
        if(this.props.autoCloseBack){
            this.props.autoCloseBack();
        }
    },
    _maskLayer: function () {
        if(this.props.getContainer){
            this.getContainer = document.getElementsByClassName(this.props.getContainer)[0];
        }else {
            this.getContainer = document.body;
        }
        this.divEL = document.createElement('div');
        this.divEL.className = "layer-background";
        this.getContainer.appendChild(this.divEL);
        this.props.shadeClose ?
            myAddEvent(this.divEL, 'click', this._handleMaskLayerClick) : "";
        //this.divEL.addEventListener("click", this._handleMaskLayerClick) : "";
    },
    _handleMaskLayerClick: function () {
        //遮罩层点击
        this.layerClose();
    },
    _setPosition: function (t) {
        //浏览器窗口宽高兼容写法
        this.windowWidth = (document.documentElement.scrollWidth > document.documentElement.clientWidth) ? document.documentElement.scrollWidth : document.documentElement.scrollWidth;
        this.windowHeight = (document.documentElement.scrollHeight > document.documentElement.clientHeight) ? document.documentElement.scrollHeight : document.documentElement.clientHeight;

        //如果设定了高宽，则使用设定的
        this.layerWidth = this.props.width ? this.props.width : this.refs.ucslayer.offsetWidth;
        this.layerHeight = this.props.height ? this.props.height : this.refs.ucslayer.offsetHeight;
        this.layerHeight = this.layerHeight > this.windowHeight ? this.windowHeight : this.layerHeight;//如果弹层高度大于浏览器窗口高，则使用浏览器窗口高
        var scrollTop = 0;// 滚动条的高度
        if (this.props.position == "absolute") {
            if (document.documentElement && document.documentElement.scrollTop) {
                scrollTop = document.documentElement.scrollTop;
            }
            else if (document.body) {
                scrollTop = document.body.scrollTop;
            }
        }
        var left = (parseInt(this.windowWidth) - parseInt(this.layerWidth)) / 2;
        var top = (parseInt(document.body.clientHeight) - parseInt(this.layerHeight)) / 2;
        if (t !== "resize") {
            this.refs.ucslayer.style.width = this.layerWidth;
            this.refs.ucslayer.style.height = this.layerHeight;
        }
        this.refs.ucslayer.style.left = left + "px";
        this.refs.ucslayer.style.top = top < 0 ? 0 : top + "px";
        if(this.refs.layerHeader){
            this.refs.layerContent.style.height = parseInt(this.layerHeight) - parseInt(this.refs.layerHeader.offsetHeight);
        }else{
            this.refs.layerContent.style.height = parseInt(this.layerHeight);
        }

    },
    _handleCloseClick: function () {
        //点击关闭时
        this.props.closeBack ? this.props.closeBack() : this.layerClose();
    },
    _handleConfirmClick: function () {
        //确认按钮点击时
        this.props.confirmBack ? this.props.confirmBack() : this.layerClose();
    },
    _handleCancelClick: function () {
        //取消按钮点击时
        this.props.cancelBack ? this.props.cancelBack() : this.layerClose();
    },
    _handleMousedown: function (e) {
        if (this.props.move) {
            this.mx = e.pageX - parseInt(this.refs.ucslayer.style.left);
            this.my = e.pageY - parseInt(this.refs.ucslayer.style.top);
            this.move = true;
            myAddEvent(document, 'mousemove', this._handleMouseMove.bind(this));
            myAddEvent(document, 'mouseup', this._handleMouseUp.bind(this));
        }
    },
    _handleMouseMove: function (e) {
        if (this.move) {
            e = event || window.event;
            var x = e.clientX - parseInt(this.mx);
            var y = e.clientY - parseInt(this.my);

            var documentHeight = document.documentElement.clientHeight;
            if (x <= 0) {
                x = 0
            } else if (x > parseInt(this.windowWidth) - parseInt(this.layerWidth)) {
                //window窗口宽－弹层宽
                x = parseInt(this.windowWidth) - parseInt(this.layerWidth)
            }
            if (y <= 0) {
                y = 0
            } else if (y > documentHeight - parseInt(this.layerHeight)) {
                y = documentHeight - parseInt(this.layerHeight)
            }
            this.refs.ucslayer.style.left = x + "px";
            this.refs.ucslayer.style.top = y + "px";
            return false;
        }
    },
    _handleMouseUp: function () {
        this.move = false;
        myRemoveEvent(document, 'mousemove', this._handleMouseMove.bind(this));
        myRemoveEvent(document, 'mouseup', this._handleMouseUp.bind(this));

    },
    render:function(){
        window._tmpid1 = window._tmpid1||1;
        var props = this.props;
        var style = "width:" + props.width + ";" + "height:" + props.height + ";"+ "display:"+this.state.display + ";"+ "position:"+ props.position+";";
        var bodyClass = "ucs-layer-body "+(props.type?"ucs-layer-text":"");
        var bodyContent = "";
        if (props.type === "text") {
            //纯文字
            bodyContent = (<div className="ucs-layer-txt">{props.children}</div>);
        } else if (props.type === "success") {
            //成功时
            bodyContent = (
                <div className="ucs-layer-success">
                    <i className="iconfont icon-success icon"></i>
                    {props.children}
                </div>
            )
        }
        else if (props.type === "failure") {
            //失败时
            bodyContent = (
                <div className="ucs-layer-failure">
                    <i className="iconfont icon-failure icon"></i>
                    {props.children}
                </div>
            )
        } else {
            //其它
            bodyContent = props.children
        }
        var close = (
                props.showClose ? <a href="javascript:;" className="ucs-layer-close iconfont icon-close" onClick={this._handleCloseClick.bind(this)}></a> : ""
            )
            ;
        var button = "";
        if (props.confirm || props.cancel) {
            button = (
                <div className="ucs-layer-footer">
                    {props.confirm ? <Button className="ucs-btn-confirm" onClick={this._handleConfirmClick.bind(this)} buttonType="confirm" value={props.confirm}></Button> : ""}
                    {props.cancel ? <Button className="ucs-btn-cancel" onClick={this._handleCancelClick.bind(this)} buttonType="cancel" value={props.cancel}></Button> : ""}
                </div>
            );
        }
        var autoClose = (
            this.props.autoClose > 0 ? <div className="ucs-autoclose"><span ref="autoClose">{this.props.autoClose}</span>秒后自动关闭!</div> : ""
        );
        var moveStyle = {cursor:(this.props.move ? "move;" : ";")};
        window._tmpid1++;
        return (
            <div id={window._tmpid1} className={"ucs-layer "+props.className+" "+props.animation} style={{display:this.state.display}} ref="ucslayer">
                {close}
                {props.title ? <div className="ucs-layer-header" onmousedown={this._handleMousedown.bind(this)} ref="layerHeader" style={moveStyle}>{props.title}</div> : ""}
                {autoClose}
                <div className="ucs-layer-content" ref="layerContent" style={{height:props.contentHeight}}>
                    <div className={bodyClass}>{bodyContent}</div>
                    {button}
                </div>
            </div>
        )
    }
});

module.exports = Layer;